'use client'
import React, { useState, useMemo } from 'react'
import { Space, Table, Tag, Button, Tabs, Input, Select, DatePicker, message, Modal, Form } from 'antd';
import {
    WechatOutlined,
    SignatureOutlined,
    VerticalAlignTopOutlined,
    DeleteOutlined,
    PlusOutlined,
    VerticalAlignBottomOutlined,
    RetweetOutlined, ImportOutlined,
    SearchOutlined,
    UndoOutlined,
    FunnelPlotOutlined
} from '@ant-design/icons';
interface OrderForm {
    id?: number;  // 添加id字段，编辑时需要
    key: string;
    name: string;
    kehu: string;
    Collor: string;
    price: number;
    yprice: number;
    kprice: number;
}

export default function page() {
    const [searchText, setSearchText] = useState(''); // 搜索关键词
    const [approvalStatus, setApprovalStatus] = useState(''); // 审批状态
    const [executionStatus, setExecutionStatus] = useState(''); // 执行状态
    const [paymentMethod, setPaymentMethod] = useState(''); // 付款方式
    const [signDate, setSignDate] = useState(null); // 签单时间
    const [filters, setFilters] = useState({
        searchText: '',
        approvalStatus: '',
        executionStatus: '',
        paymentMethod: '',
        signDate: null as any
    })

    // 添加表单相关状态
    const [formVisible, setFormVisible] = useState(false);
    const [formData, setFormData] = useState<OrderForm>({
        key: '',
        name: '',
        kehu: '',
        Collor: '未提交',
        price: 0,
        yprice: 0,
        kprice: 0
    });
    // 处理搜索：点击查询时更新过滤条件
    const handleSearch = () => {
        setFilters({
            searchText,
            approvalStatus,
            executionStatus,
            paymentMethod,
            signDate
        })
        message.success('查询成功')
    }
    // 重置搜索
    const handleReset = () => {
        setSearchText('');
        setApprovalStatus('');
        setExecutionStatus('');
        setPaymentMethod('');
        setSignDate(null);
        setFilters({  // 同时重置过滤条件
            searchText: '',
            approvalStatus: '',
            executionStatus: '',
            paymentMethod: '',
            signDate: null
        })
        message.success('搜索条件已重置');
    };
    const [isEditing, setIsEditing] = useState(false);  // 是否是编辑状态
    const [currentOrderId, setCurrentOrderId] = useState<number | null>(null);  // 当前编辑的订单ID
    const handleEdit = (record: OrderForm) => {
        setFormData({
            key: record.key,
            name: record.name,
            kehu: record.kehu,
            Collor: record.Collor,
            price: record.price,
            yprice: record.yprice,
            kprice: record.kprice
        });
        setCurrentOrderId(record.id);  // 设置当前编辑的订单ID
        setIsEditing(true);  // 设置为编辑模式
        setFormVisible(true);  // 打开模态框
    };
    const [data, setData] = useState([
        {
            id: 1,
            key: 'DD20190324010001',
            name: '订单标题1',
            kehu: ' 深圳市亿恩科技有限公司',
            Collor: '已通过',
            price: 10000,
            yprice: 10000,
            kprice: 10000,
        },
        {
            id: 2,
            key: 'DD20190324010001',
            name: '订单标题2',
            kehu: ' 深圳市亿恩科技有限公司',
            Collor: '被否决',
            price: 10000,
            yprice: 10000,
            kprice: 10000,
        },
        {
            id: 3,
            key: 'DD20190324010001',
            name: '订单标题3',
            kehu: ' 深圳市亿恩科技有限公司',
            Collor: '已撤销',
            price: 10000,
            yprice: 10000,
            kprice: 10000,
        },
        {
            id: 4,
            key: 'DD20190324010001',
            name: '订单标题4',
            kehu: ' 深圳市亿恩科技有限公司',
            Collor: '待审批',
            price: 10000,
            yprice: 10000,
            kprice: 10000,
        },
        {
            id: 5,
            key: 'DD20190324010001',
            name: '订单标题5',
            kehu: ' 深圳市亿恩科技有限公司',
            Collor: '已通过',
            price: 10000,
            yprice: 10000,
            kprice: 10000,
        },
        {
            id: 6,
            key: 'DD20190324010001',
            name: '订单标题6',
            kehu: ' 深圳市亿恩科技有限公司',
            Collor: '未提交',
            price: 10000,
            yprice: 10000,
            kprice: 10000,
        },
        {
            id: 7,
            key: 'DD20190324010001',
            name: '订单标题7',
            kehu: ' 深圳市亿恩科技有限公司',
            Collor: '已通过',
            price: 10000,
            yprice: 10000,
            kprice: 10000,
        },
        {
            id: 8,
            key: 'DD20190324010002',
            name: '订单标题8',
            kehu: ' 深圳市亿恩科技有限公司',
            Collor: '已通过',
            price: 10000,
            yprice: 10000,
            kprice: 10000,
        },
        {
            id: 9,
            key: 'DD20190324010002',
            name: '订单标题8',
            kehu: ' 深圳市亿恩科技有限公司',
            Collor: '已通过',
            price: 10000,
            yprice: 10000,
            kprice: 10000,
        },
        {
            id: 10,
            key: 'DD20190324010002',
            name: '订单标题8',
            kehu: ' 深圳市亿恩科技有限公司',
            Collor: '已通过',
            price: 10000,
            yprice: 10000,
            kprice: 10000,
        },
        {
            id: 11,
            key: 'DD20190324010002',
            name: '订单标题8',
            kehu: ' 深圳市亿恩科技有限公司',
            Collor: '已通过',
            price: 10000,
            yprice: 10000,
            kprice: 10000,
        },
        {
            id: 12,
            key: 'DD20190324010002',
            name: '订单标题8',
            kehu: ' 深圳市亿恩科技有限公司',
            Collor: '已通过',
            price: 10000,
            yprice: 10000,
            kprice: 10000,
        },
    ]);

    const handleFormSubmit = () => {
        // 验证必填字段
        if (!formData.key || !formData.name || !formData.kehu) {
            message.error('请填写必填字段');
            return;
        }

        if (isEditing && currentOrderId) {
            // 编辑模式 - 更新现有订单
            setData(data.map(item =>
                item.id === currentOrderId ? { ...item, ...formData } : item
            ));
            message.success('订单更新成功');
        } else {
            // 添加模式 - 创建新订单
            const newId = data.length > 0 ? Math.max(...data.map(item => item.id)) + 1 : 1;
            const newOrder = {
                id: newId,
                ...formData
            };
            setData([...data, newOrder]);
            message.success('订单添加成功');
        }

        // 重置表单状态
        setFormData({
            key: '',
            name: '',
            kehu: '',
            Collor: '未提交',
            price: 0,
            yprice: 0,
            kprice: 0
        });
        setIsEditing(false);
        setCurrentOrderId(null);
        setFormVisible(false);
    };
    // 根据搜索条件过滤数据
    const filteredData = useMemo(() => {
        return data.filter(item => {
            // 关键词搜索（订单编号、订单标题、客户名称）
            const keywordMatch = filters.searchText === '' ||
                item.key.toLowerCase().includes(searchText.toLowerCase()) ||
                item.name.toLowerCase().includes(searchText.toLowerCase()) ||
                item.kehu.toLowerCase().includes(searchText.toLowerCase());

            // 审批状态筛选
            const approvalMatch = filters.approvalStatus === '' || item.Collor === filters.approvalStatus;

            // 其他筛选条件可以根据需要添加

            return keywordMatch && approvalMatch;
        });
    }, [data, searchText, approvalStatus, executionStatus, paymentMethod, signDate, filters]);

    const columns = [
        {
            title: '订单编号',
            dataIndex: 'key',
            sorter: {
                compare: (a: any, b: any) => a.key.localeCompare(b.key),
                multiple: 3,
            },
            render: (key: any) => {
                return <div>{key}</div>;
            }
        },
        {
            title: '订单标题',
            dataIndex: 'name',
            sorter: {
                compare: (a: any, b: any) => a.name.localeCompare(b.name),
                multiple: 3,
            },
            render: (name: any) => {
                return <div style={{ color: '#1777FF' }}>{name}</div>;
            }
        },
        {
            title: '关联客户',
            dataIndex: 'kehu',
            sorter: {
                compare: (a: any, b: any) => a.kehu.localeCompare(b.kehu),
                multiple: 3,
            },
            render: (kehu: any) => {
                return <div style={{ color: '#1777FF' }}>{kehu}</div>;
            }
        },
        {
            title: '审批状态',
            dataIndex: 'Collor',
            sorter: {
                compare: (a: any, b: any) => a.Collor.localeCompare(b.Collor),
                multiple: 3,
            },
            render: (Collor: any) => {
                if (Collor === "已通过") {
                    return <Tag color="green">{Collor}</Tag>;
                } else if (Collor === "被否决") {
                    return <Tag color="red">{Collor}</Tag>;
                } else if (Collor === "已撤销") {
                    return <Tag color="orange">{Collor}</Tag>;
                } else if (Collor === "待审批") {
                    return <Tag color="blue">{Collor}</Tag>;
                } else if (Collor === '未提交') {
                    return <Tag color="gray">{Collor}</Tag>;
                }
            },
        },
        {
            title: '订单总金额',
            dataIndex: 'price',
            sorter: {
                compare: (a: any, b: any) => a.price - b.price,
                multiple: 3,
            },
            render: (price: any) => {
                return <div>￥{price}.00</div>;
            }
        },
        {
            title: '已回款金额',
            dataIndex: 'yprice',
            sorter: {
                compare: (a: any, b: any) => a.yprice - b.yprice,
                multiple: 3,
            },
            render: (yprice: any) => {
                return <div>￥{yprice}.00</div>;
            }
        },
        {
            title: '已开票金额 ',
            dataIndex: 'kprice',
            sorter: {
                compare: (a: any, b: any) => a.kprice - b.kprice,
                multiple: 3,
            },
            render: (kprice: any) => {
                return <div>￥{kprice}.00</div>;
            }
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record: any) => (
                <Space size="middle">
                    <a onClick={() => {
                        //跟进操作
                        alert('跟进成功');
                    }}><WechatOutlined />跟进</a>
                    <a onClick={() => handleEdit(record)}><SignatureOutlined />编辑</a>
                    <a onClick={() => {
                        //置顶操作
                        const newData = data.filter((item) => item.id !== record.id);
                        setData([record, ...newData]);
                    }}><VerticalAlignTopOutlined />置顶</a>
                    <a onClick={() => {
                        //删除操作
                        const newData = data.filter((item) => item.id !== record.id);
                        setData(newData);
                    }}><DeleteOutlined />删除</a>
                </Space>
            ),
        },
    ];

    const items = [
        {
            key: '1',
            label: '全部订单',
            children: <>
                <Space>
                    <Input placeholder="搜索关键字"
                        style={{ width: '200px' }}
                        value={searchText}
                        onChange={(e) => setSearchText(e.target.value)}
                    />
                    <Select
                        style={{ width: '200px' }}
                        defaultValue="审批状态"
                        value={approvalStatus}
                        onChange={setApprovalStatus}
                        options={[
                            { value: '已通过', label: '已通过' },
                            { value: '被否决', label: '被否决' },
                            { value: '已撤销', label: '已撤销' },
                            { value: '待审批', label: '待审批' },
                            { value: '未提交', label: '未提交' }
                        ]}
                    />
                    <Select defaultValue="执行状态"
                        style={{ width: '200px' }}
                        // value={executionStatus}
                        onChange={setExecutionStatus}
                        options={[
                            { value: '执行中', label: '执行中' },
                            { value: '已完成', label: '已完成' },
                            { value: '已取消', label: '已取消' }
                        ]}
                    />
                    <DatePicker placeholder='签单时间'
                        value={signDate}
                        onChange={setSignDate} />
                    <Select placeholder="付款方式"
                        defaultValue="付款方式"
                        style={{ width: '200px' }}
                        // value={paymentMethod}
                        onChange={setPaymentMethod}
                        options={[
                            { value: '现金', label: '现金' },
                            { value: '转账', label: '转账' },
                            { value: '支票', label: '支票' },
                            { value: '信用卡', label: '信用卡' }
                        ]}
                    />
                    <Button type="primary" onClick={handleSearch}>
                        <SearchOutlined />查询
                    </Button>
                    <Button onClick={handleReset}>
                        <UndoOutlined />重置
                    </Button>
                    <div style={{ color: 'blue' }}>
                        <FunnelPlotOutlined />高级搜索
                    </div>
                </Space>
            </>,
        },
        {
            key: '2',
            label: '我的订单',
            children: '我的订单',
        },
        {
            key: '3',
            label: '下属订单',
            children: '下属订单',
        },
        {
            key: '4',
            label: '我的协作',
            children: '我的协作',
        },
        {
            key: '5',
            label: '下属协作',
            children: '下属协作',
        },
    ];

    const onChange = (key: any) => {
        console.log(key);
    };

    return (
        <div>
            <div>
                {/* 添加订单模态框 */}
                <Modal
                    title={isEditing ? "编辑订单" : "添加新订单"}
                    open={formVisible}
                    onOk={handleFormSubmit}
                    onCancel={() => {
                        setFormVisible(false)
                        setIsEditing(false);
                        setCurrentOrderId(null);
                        setFormData({
                            key: '',
                            name: '',
                            kehu: '',
                            Collor: '未提交',
                            price: 0,
                            yprice: 0,
                            kprice:0
                        })
                    }}
                    okText="确认"
                    cancelText="取消"
                >
                    <Form layout="vertical">
                        <Form.Item label="订单编号" required>
                            <Input
                                value={formData.key}
                                onChange={(e) => setFormData({ ...formData, key: e.target.value })}
                                placeholder="请输入订单编号"
                            />
                        </Form.Item>
                        <Form.Item label="订单标题" required>
                            <Input
                                value={formData.name}
                                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                placeholder="请输入订单标题"
                            />
                        </Form.Item>
                        <Form.Item label="关联客户" required>
                            <Input
                                value={formData.kehu}
                                onChange={(e) => setFormData({ ...formData, kehu: e.target.value })}
                                placeholder="请输入关联客户"
                            />
                        </Form.Item>
                        <Form.Item label="审批状态">
                            <Select
                                value={formData.Collor}
                                onChange={(value) => setFormData({ ...formData, Collor: value })}
                            >
                                <Select.Option value="已通过">已通过</Select.Option>
                                <Select.Option value="被否决">被否决</Select.Option>
                                <Select.Option value="已撤销">已撤销</Select.Option>
                                <Select.Option value="待审批">待审批</Select.Option>
                                <Select.Option value="未提交">未提交</Select.Option>
                            </Select>
                        </Form.Item>
                        <Form.Item label="订单总金额" required>
                            <Input
                                type="number"
                                value={formData.price}
                                onChange={(e) => setFormData({ ...formData, price: Number(e.target.value) })}
                                placeholder="请输入订单总金额"
                            />
                        </Form.Item>
                        <Form.Item label="已回款金额" required>
                            <Input
                                type="number"
                                value={formData.yprice}
                                onChange={(e) => setFormData({ ...formData, yprice: Number(e.target.value) })}
                                placeholder="请输入已回款金额"
                            />
                        </Form.Item>
                        <Form.Item label="已开票金额" required>
                            <Input
                                type="number"
                                value={formData.kprice}
                                onChange={(e) => setFormData({ ...formData, kprice: Number(e.target.value) })}
                                placeholder="请输入已开票金额"
                            />
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
            <div style={{ margin: '0 0 50px 0' }}>
                <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
            </div>
            <Space>
                <Button color="primary" variant="solid" onClick={() => setFormVisible(true)}><PlusOutlined />添加</Button>
                <Button color="default" variant="outlined"><VerticalAlignBottomOutlined />导入</Button>
                <Button color="default" variant="outlined"><VerticalAlignTopOutlined />导出</Button>
                <Button color="default" variant="outlined"><RetweetOutlined />转移订单</Button>
                <Button color="default" variant="outlined"><ImportOutlined />添加协作</Button>
            </Space>
            <Table rowKey='id' columns={columns} dataSource={filteredData} pagination={{ defaultPageSize: 8 }} />
        </div>
    );
}
